package com.originskyseed.platform.login.controller;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.bingoohuang.patchca.service.Captcha;
import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.config.LoginConfig;
import com.originskyseed.platform.common.api.constant.RedisKeyConstans;
import com.originskyseed.platform.common.api.constant.WebappKeyConstants;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.config.bean.ConfigManager;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.filter.util.FilterCacheUtil;
import com.originskyseed.platform.core.filter.util.FilterSystemTypeUtil;
import com.originskyseed.platform.core.redis.util.RedisUtil;
import com.originskyseed.platform.core.util.bean.AccessObjectUtil;
import com.originskyseed.platform.core.util.bean.ImageCodeUtil;
import com.originskyseed.platform.core.util.bean.security.KeyUtil;
import com.originskyseed.platform.login.i18n.LoginResponseMsg;
import com.originskyseed.platform.login.vo.request.VerificationRequestVO;
import com.originskyseed.platform.login.vo.response.GetKeyResponseVO;
import com.originskyseed.platform.login.vo.response.VerificationResponseVO;
import com.originskyseed.platform.role.model.Menu;
import com.originskyseed.platform.role.model.Role;
import com.originskyseed.platform.role.service.IMenuService;
import com.originskyseed.platform.role.service.IRoleService;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.TradeUnion;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.model.UserLoginLock;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.ITradeUnionService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.service.IUserLoginLockService;

/**
 * 登录Controller类
 *
 * @author LiangMingHui
 */
@Controller
@RequestMapping("/login")
@BaseLocaleResource(localeFileName = "i18n_login")
public class LoginController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IRoleService roleService;

	@DubboReference
	private IMenuService menuService;

	@DubboReference
	private ITradeUnionService tradeUnionService;

	@DubboReference
	private IUserLoginLockService userLoginLockService;

	@DubboReference
	private IDeptService deptService;

	/**
	 * 获取图形验证码
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/getImageCode.json")
	public void getImageCode(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 获取验证码
			Captcha captcha = ImageCodeUtil.getCaptcha();
			String currentSessionId=request.getParameter("sessionId");

			String serverSessionId=request.getSession().getId();
            //System.out.println("==currentSessionId===1=="+currentSessionId+"==serverSessionId=="+serverSessionId);
			request.getSession().setAttribute(WebappKeyConstants.IMAGE_CODE_KEY, captcha.getChallenge());

			// 生成验证码
			ImageCodeUtil.writeImage(captcha, response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 获取密钥
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getKey.json")
	public BaseResponseBody getKey(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result = null;
		try {
			// 获取公钥和私钥
			HashMap<String, Object> keys = KeyUtil.getKeys();
			RSAPublicKey publicKey = (RSAPublicKey) keys.get("public");
			RSAPrivateKey privateKey = (RSAPrivateKey) keys.get("private");

			if (null != publicKey && null != privateKey) {
				// 保存私钥到Session
				request.getSession().setAttribute(WebappKeyConstants.PRIVATE_KEY_KEY, privateKey);

				// 将公钥传到前端
				GetKeyResponseVO responseVO = new GetKeyResponseVO();
				responseVO.setModulus(publicKey.getModulus().toString(16));
				responseVO.setExponent(publicKey.getPublicExponent().toString(16));
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_GET_KEY_SUCCESS.getMsg()), responseVO);
			} else {
				result = new BaseResponseBody(true, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_GET_KEY_ERROR.getMsg()), null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_GET_KEY_ERROR.getMsg()), null);
		}
		return result;
	}

	/**
	 * 登录验证
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/verification.json")
	@RequiredParams(names = { "account", "password" })
	@SysLog(module = "登录", operationDesc = "用户登录")
	public BaseResponseBody verification(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result = null;
		try {
			long startime=System.currentTimeMillis();
			// 请求对象
			VerificationRequestVO requestVO = this.getParameterBean(VerificationRequestVO.class);
			// 登录参数配置
			LoginConfig loginConfig = ConfigManager.getInstance().parseObject(LoginConfig.class);
			// 获取密码
			String decryptedPassword = requestVO.getPassword();
            //System.out.println("==sessionId=0="+request.getSession().getId());
			// 根据私钥获取密码
			RSAPrivateKey privateKey = (RSAPrivateKey) request.getSession().getAttribute(WebappKeyConstants.PRIVATE_KEY_KEY);
			if (null != privateKey) {
				decryptedPassword = KeyUtil.decryptByPrivateKey(requestVO.getPassword(), privateKey);
			}
			//System.out.println("==sessionId=="+request.getSession().getId());
			//System.out.println("===code=="+requestVO.getCode()+"===codeKey=="+request.getSession().getAttribute(WebappKeyConstants.IMAGE_CODE_KEY));
			//System.out.println("==1="+StringUtils.equalsIgnoreCase(requestVO.getCode(), (String) (request.getSession().getAttribute(WebappKeyConstants.IMAGE_CODE_KEY))));
			//System.out.println("=2=="+StringUtils.equalsIgnoreCase(requestVO.getCode(), loginConfig.getUniversalVerificationCode()));
			// 判断验证码
			if (!StringUtils.equalsIgnoreCase(requestVO.getCode(), (String) (request.getSession().getAttribute(WebappKeyConstants.IMAGE_CODE_KEY))) && !StringUtils.equalsIgnoreCase(requestVO.getCode(), loginConfig.getUniversalVerificationCode()) ) {
				return new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_IMAGE_CODE_ERROR.getMsg()), null);
			}
			// 判断账号和密码
			UserInfo userInfo = (UserInfo) RedisUtil.getInstance().getForMap(RedisKeyConstans.getTenantCodeAndRedisKey(RedisKeyConstans.REDIS_USER_INFO_KEY), requestVO.getAccount());
			if (userInfo != null) {
				if (!userInfo.getPassword().equals(DigestUtils.md5DigestAsHex(decryptedPassword.getBytes()))) {
					return new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_PASSWORD_ERROR.getMsg()), null);
				}
			} else {
				userInfo = this.userInfoService.selectByAccountAndPassword(requestVO.getAccount(), decryptedPassword);
			}

			if (null != userInfo) {
				if (userInfo.getStatus() == 1) {
					if (userInfo.getIsDel() == 1) {
						result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_DEL.getMsg()), null);
					} else {
						// 为主播则要判断签约时间,一个月未签约则不能登录
						/*if(userInfo.getType()==11 && StringUtils.isNotBlank(userInfo.getOtherAccount())){
							Date date = new Date();
							Date loginDate = userInfo.getCreateTime();
							long day = (date.getTime() - loginDate.getTime()) / (24 * 60 * 60 * 1000);
							if(day>30){
								TreeMap<String,Object> param = new TreeMap<>();
								param.put("anchorId",userInfo.getOtherAccount());
								Map map = QueryAppUtil.query("anchorInfoUrl",1,param);
								Integer code = Integer.parseInt(map.get("code").toString());
								if (code == 1) {
									String data = (String) map.get("data");
									JSONObject jsonObject = JSONObject.parseObject(data);
									if(jsonObject.containsKey("signContractDate")){
										String signContractDate = (String) jsonObject.get("signContractDate");
										if(StringUtils.isBlank(signContractDate)){
											return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.NOT_SIGNED_UNABLE_TO_LOG_IN.getMsg()), null);
										}
									}else {
										return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.NOT_SIGNED_UNABLE_TO_LOG_IN.getMsg()), null);
									}
								}else {
									return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.NOT_SIGNED_UNABLE_TO_LOG_IN.getMsg()), null);
								}
							}
						}*/
						// 登录最大间隔时间
						Integer maxLoginIntervalDate = loginConfig.getMaxLoginIntervalDate();
						Date date = new Date();
						Date loginDate = userInfo.getFinallyLoginTime();
						if (loginDate == null) {
							loginDate = userInfo.getCreateTime();
						}
						// 得到相隔的天数
						long day = (date.getTime() - loginDate.getTime()) / (24 * 60 * 60 * 1000);
						// 相隔的天数大于最大的登录间隔天数,并且账号不等于admin
						if (day > maxLoginIntervalDate && !"admin".equals(userInfo.getAccount())) {
							UserInfo updateUserInfo = new UserInfo();
							updateUserInfo.setId(userInfo.getId());
							updateUserInfo.setFinallyLoginTime(new Date());
							updateUserInfo.setStatus(5);
							this.userInfoService.updateByPrimaryKeySelective(updateUserInfo);
							return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ACCOUNT_FROZEN_ERROR.getMsg()), false);
						}
						// 查询该账户所属的角色
						List<Role> listRole = this.roleService.selectByUserId(userInfo.getId());
						if (listRole.size() > 0) {
							String roleCode = listRole.get(0).getCode();
							userInfo.setRoleId(listRole.get(0).getId());
							userInfo.setRoleName(listRole.get(0).getName());
							userInfo.setRoleCode(roleCode);

							// 删除输错密码次数
							UserLoginLock userLoginLock2 = new UserLoginLock();
							userLoginLock2.setAccount(userInfo.getAccount());
							List<UserLoginLock> userLoginLockList = this.userLoginLockService.selectList(userLoginLock2);
							if (userLoginLockList.size() > 0) {
								for (UserLoginLock userLoginLock : userLoginLockList) {
									this.userLoginLockService.deleteByPrimaryKey(userLoginLock.getId());
								}
							}

							// 判断是否第一次登录
							if (userInfo.getFinallyLoginTime() == null) {
								userInfo.setIsFirstLogin(1);
								userInfo.setIsSameDayFirstLogin(1);
								request.getSession().setAttribute("roleCode", roleCode);
								request.getSession().setAttribute("userInfo", userInfo);
								JSONObject jsonObject = new JSONObject();
								jsonObject.put("code", 6000);
								jsonObject.put("phone", userInfo.getPhone());
								return new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_VERIFICATION_SUCCESS.getMsg()), jsonObject);
								// 判断是否当天第一次登录
							} else {
								Date loginTime = userInfo.getFinallyLoginTime();
								boolean flag = isToday(loginTime);
								if (!flag) {
									request.getSession().setAttribute("roleCode", roleCode);
									request.getSession().setAttribute("userInfo", userInfo);
									JSONObject jsonObject = new JSONObject();
									jsonObject.put("code", 6000);
									jsonObject.put("phone", userInfo.getPhone());
									return new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_VERIFICATION_SUCCESS.getMsg()), jsonObject);
								}
							}
							// 最大修改密码间隔时间
							Integer maxUpdatePasswordDate = loginConfig.getMaxUpdatePasswordDate();
							date = new Date();
							Date updatePassTime = userInfo.getUpdatePassTime();
							if (updatePassTime == null) {
								updatePassTime = userInfo.getCreateTime();
							}
							// 得到相隔的天数
							day = (date.getTime() - updatePassTime.getTime()) / (24 * 60 * 60 * 1000);
							// 相隔的天数大于最大的登录间隔天数
							if (day > maxUpdatePasswordDate) {
								JSONObject jsonObject = new JSONObject();
								jsonObject.put("code", 6001);
								jsonObject.put("phone", userInfo.getPhone());
								return new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.OVERTIME_NOT_UPDATE_PASSWORD.getMsg()), jsonObject);
							}
							// 获取客户端系统类型
							String clientSystemType = FilterSystemTypeUtil.getInstance().getClientSystemType(request, response);
							// 创建相关缓存
							String tokenValue = this.createCache(clientSystemType, userInfo, null);
							request.getSession().setAttribute("roleCode", roleCode);
							// 返回登录验证响应VO（供前端HTML写入Header等缓存）
							VerificationResponseVO responseVO = new VerificationResponseVO();
							// 获取公会审核状态
							TradeUnion tradeUnion = this.tradeUnionService.selectByUserId(userInfo.getId());
							if (tradeUnion != null) {
								responseVO.setStatus(tradeUnion.getAuditStatus());
								responseVO.setTradeUnion(tradeUnion);
							}
							responseVO.setSource(userInfo.getSourceSys());
							responseVO.setTokenCookieValue(tokenValue);
							result = new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_VERIFICATION_SUCCESS.getMsg()), responseVO);
						} else {
							result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.NOT_BING_ROLE_ERROR.getMsg()), null);
						}
					}
				} else if (userInfo.getStatus() == 4) {
					result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ACCOUNT_LOCKING_ERROR.getMsg()), null);
				} else if (userInfo.getStatus() == 5) {
					result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ACCOUNT_FROZEN_ERROR.getMsg()), null);
				} else {
					result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_PROHIBIT.getMsg()), null);
				}
			} else {
				UserInfo userInfo1 = this.userInfoService.selectByAccount(requestVO.getAccount());
				// admin不用判断
				if (userInfo1 != null && userInfo1.getAccount() != "admin") {
					if (userInfo1.getStatus() == 4) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ACCOUNT_LOCKING_ERROR.getMsg()), false);
						// return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_PASSWORD_ERROR.getMsg()), false);

					}
					// 最大登录次数
					Integer errorFrequency = 10;
					UserLoginLock userLoginLock2 = new UserLoginLock();
					userLoginLock2.setAccount(userInfo1.getAccount());
					List<UserLoginLock> userLoginLockList = this.userLoginLockService.selectList(userLoginLock2);
					if (userLoginLockList.size() > 0) {
						UserLoginLock userLoginLock = userLoginLockList.get(0);
						if (userLoginLock.getNum() + 1 >= errorFrequency) {
							UserInfo updateUserInfo = new UserInfo();
							updateUserInfo.setStatus(4);
							updateUserInfo.setAccount(requestVO.getAccount());
							updateUserInfo.setUpdateTime(new Date());
							this.userInfoService.updateByAccount(updateUserInfo);
							return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_PASSWORD_ERROR.getMsg()), false);
						} else {
							userLoginLock.setNum(userLoginLock.getNum() + 1);
							userLoginLock.setUpdateTime(new Date());
							this.userLoginLockService.updateByPrimaryKeySelective(userLoginLock);
						}
					} else {
						UserLoginLock userLoginLock1 = new UserLoginLock();
						userLoginLock1.setAccount(requestVO.getAccount());
						userLoginLock1.setNum(1);
						userLoginLock1.setName(userInfo1.getName());
						this.userLoginLockService.insertSelective(userLoginLock1);
					}
					result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_PASSWORD_ERROR.getMsg()), false);
				} else {
					result = new BaseResponseBody(false, CommonResponseCode.FAILURE_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_ACCOUNT_PASSWORD_ERROR.getMsg()), false);
				}
			}
			//System.out.println("==verification.json=="+(System.currentTimeMillis()-startime)/1000+"==="+(System.currentTimeMillis()-startime));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.LOGIN_VERIFICATION_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 判断日期是否为当天
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public static boolean isToday(Date date) {
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date);
		int year1 = c1.get(Calendar.YEAR);
		int month1 = c1.get(Calendar.MONTH) + 1;
		int day1 = c1.get(Calendar.DAY_OF_MONTH);

		Calendar c2 = Calendar.getInstance();
		c2.setTime(new Date());
		int year2 = c2.get(Calendar.YEAR);
		int month2 = c2.get(Calendar.MONTH) + 1;
		int day2 = c2.get(Calendar.DAY_OF_MONTH);
		if (year1 == year2 && month1 == month2 && day1 == day2) {
			return true;
		}
		return false;
	}

	/**
	 * 修改公会信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateTradeUnion.json")
	public BaseResponseBody updateTradeUnion(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			TradeUnion tradeUnion = this.getParameterBean(TradeUnion.class);
			tradeUnion.setUserId(userInfo.getId());
			tradeUnion.setUpdateTime(new Date());
			this.tradeUnionService.updateByUserId(tradeUnion);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ERROR.getMsg()), null);
		}
		return result;
	}


	/**
	 * 查询当前用户公会信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectTradeUnion.json")
	public BaseResponseBody selectTradeUnion(HttpServletRequest request, HttpServletResponse response) {

		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (userInfo == null) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ACCOUNT_ISNULL.getMsg()), null);
			} else {
				String otherAccount = userInfo.getOtherAccount();
				if (otherAccount == null || StringUtils.isBlank(otherAccount)) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.USER_OTHER_ACCONUT_ISNULL.getMsg()), null);
				}
				TradeUnion tradeUnion = null;
				// 请求接口
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("channelId", otherAccount);
				Map resultMap = QueryAppUtil.query("queryUnionUrl", 1, paramMap);
				Integer code = Integer.parseInt(resultMap.get("code").toString());
				String msg = (String) resultMap.get("msg");
				if (code == 1) {
					// json字符串转jsonArray
					String data = (String) resultMap.get("data");
					tradeUnion = JsonUtils.parse(data, TradeUnion.class);
					result = new BaseResponseBody(true, CommonResponseCode.SUCCESS_AUTHENTICATION.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.SUCCESS.getMsg()), tradeUnion);
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), "") + " msg: " + msg, null);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LoginResponseMsg.ERROR.getMsg()), null);
		}
		return result;
	}

	/**
	 * 创建相关缓存
	 *
	 * @param systemType
	 * @param userInfo
	 * @param tenantAppCodeList
	 * @return
	 * @throws Exception
	 */
	private String createCache(String systemType, UserInfo userInfo, List<Map<String, Object>> tenantAppCodeList) throws Exception {

		String roleName = userInfo.getRoleName();
		String roleCode = userInfo.getRoleCode();
		String roleId = userInfo.getRoleId();
		Integer isFirstLogin = userInfo.getIsFirstLogin();
		Integer isSameDayFirstLogin = userInfo.getIsSameDayFirstLogin();

		// 更新用户信息
		userInfo = this.userInfoService.updateLoginInfo(userInfo.getId(), AccessObjectUtil.getClientAddress());
		userInfo.setRoleName(roleName);
		userInfo.setRoleCode(roleCode);
		userInfo.setRoleId(roleId);
		userInfo.setIsFirstLogin(isFirstLogin);
		userInfo.setIsSameDayFirstLogin(isSameDayFirstLogin);

		// 获取角色信息
		List<Role> roleList = this.roleService.selectByUserId(userInfo.getId());

		// 获取权限信息
		List<Menu> permissionList = this.menuService.selectByUserId(userInfo.getId());

		// 创建相关缓存
		return FilterCacheUtil.createCache(systemType, userInfo.getAccount(), userInfo, roleList, permissionList, tenantAppCodeList, null, null, null);
	}

	/**
	 * 查找推广体系
	 * 
	 * @return
	 */
	private Dept selectTopDept(String code) throws Exception {
		Dept dept = this.deptService.selectByCode(code);
		if (dept.getType() == 1) {
			return dept;
		} else {
			return selectTopDept(dept.getParentCode());
		}
	}
}
